/**
 * 
 * @param {Blob} data 
 * @param {*} options 
 */
export async function saveFile(data, options = {}) {
    const opts = {
        types: [
            {
                description: options.desc,
                accept: { "text/plain": [options.ext] },
            },
        ],
    };
    const file = await window.showSaveFilePicker(opts);
    console.log('%c 测试有啥', 'color: #004', file);
    const write = await file.createWritable();
    console.log('%c 怎么写入', 'color: #009', write);
    await write.write(data);
    console.log('%c 我快要好了', 'color: #00d', data);
    // console.log('%c 我快要好了', 'color: #00e', (await data.arrayBuffer()));
    
    await write.close();
}

export async function openFile(options = {}) {
    const opts = {
        types: [
            {
                description: options.desc,
                accept: options.accept
            },
        ],
        excludeAcceptAllOption: true,
        multiple: false,
    };
    const [fileHandle] = await window.showOpenFilePicker(opts);
    console.log('%c 打开文件', 'color: #006', fileHandle);
    const fileData = await fileHandle.getFile();
    return fileData;
}

export function dataURLtoBlob(dataurl) {
    console.log('%c dataurl', 'color: #008', dataurl)
    var arr = dataurl.split(',');
    var mime = arr[0].match(/:(.*?);/)[1];
    var bstr = atob(arr[1]);
    console.log('%c 看看这个', 'color: #00c', bstr);
    var n = bstr.length;
    var u8arr = new Uint8Array(n);
    
    while(n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    console.log('%c 写的啥玩意儿', 'color: #00a', mime);
    const rel = new Blob([u8arr], {type: mime});
    console.log('%c 内容是', 'color: #00b', rel);
    // return rel
    return u8arr
}